package com.crm.custinfo.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.ConfigConstant;
import com.ruoyi.common.constant.StatusConstant;
import com.ruoyi.common.constant.TypeConstant;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.framework.datasource.DynamicDataSourceContextHolder;
import com.ruoyi.framework.websocket.WebSocketServer;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.crm.custinfo.mapper.CustNoticeInfoMapper;
import com.crm.custinfo.domain.CustNoticeInfo;
import com.crm.custinfo.service.ICustNoticeInfoService;

/**
 * 备忘录Service业务层处理
 *
 * @author ruoyi
 * @date 2024-01-12
 */
@Service
public class CustNoticeInfoServiceImpl implements ICustNoticeInfoService {
    protected Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private CustNoticeInfoMapper custNoticeInfoMapper;

    @Autowired
    private ISysConfigService baseSysConfigService;
    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private WebSocketServer webSocket;

    /**
     * 查询备忘录
     *
     * @param id 备忘录主键
     * @return 备忘录
     */
    @Override
    public CustNoticeInfo selectCustNoticeInfoById(Long id) {
        return custNoticeInfoMapper.selectCustNoticeInfoById(id);
    }

    /**
     * 查询备忘录列表
     *
     * @param custNoticeInfo 备忘录
     * @return 备忘录
     */
    @Override
    public List<CustNoticeInfo> selectCustNoticeInfoList(CustNoticeInfo custNoticeInfo) {
        return custNoticeInfoMapper.selectCustNoticeInfoList(custNoticeInfo);
    }

    /**
     * 新增备忘录
     *
     * @param custNoticeInfo 备忘录
     * @return 结果
     */
    @Override
    public int insertCustNoticeInfo(CustNoticeInfo custNoticeInfo) {
        custNoticeInfo.setCreateTime(DateUtils.getNowDate());
        return custNoticeInfoMapper.insertCustNoticeInfo(custNoticeInfo);
    }

    /**
     * 修改备忘录
     *
     * @param custNoticeInfo 备忘录
     * @return 结果
     */
    @Override
    public int updateCustNoticeInfo(CustNoticeInfo custNoticeInfo) {
        return custNoticeInfoMapper.updateCustNoticeInfo(custNoticeInfo);
    }

    /**
     * 批量删除备忘录
     *
     * @param ids 需要删除的备忘录主键
     * @return 结果
     */
    @Override
    public int deleteCustNoticeInfoByIds(Long[] ids) {
        return custNoticeInfoMapper.deleteCustNoticeInfoByIds(ids);
    }

    /**
     * 删除备忘录信息
     *
     * @param id 备忘录主键
     * @return 结果
     */
    @Override
    public int deleteCustNoticeInfoById(Long id) {
        return custNoticeInfoMapper.deleteCustNoticeInfoById(id);
    }

    /**
     * 初始化零星跟进定时通知消息
     */
    @Override
    public void initNoticeIntime() {
        logger.info("定时任务初始化零星跟进定时通知消息开始");
        List<SysUser> list = iSysUserService.selectUserByDeptids(new SysUser());
        list.stream()
                .filter(sysUser -> sysUser.getRoleKey().equals(TypeConstant.ROLE_ID_4) &&
                        sysUser.getRoleKey().equals(TypeConstant.ROLE_ID_40) &&
                        sysUser.getRoleKey().equals(TypeConstant.ROLE_ID_8))
                .collect(Collectors.toList());

        String noticeTimeStr = baseSysConfigService.getItemValueByItemKey(ConfigConstant.NOTICE_TIME_ZERO_DAILY, "11:45,17:15,20:30");
        String[] noticeTimeArr = noticeTimeStr.split(",");
        int uCount = 0;
        int nCount = 0;
        List<Long> userids = new ArrayList<Long>();
        for (SysUser user : list) {
            if(userids.contains(user.getUserId())){
                continue;
            }
            userids.add(user.getUserId());


            uCount++;
            for (String time : noticeTimeArr) {
                CustNoticeInfo noticeInfo = new CustNoticeInfo();
                noticeInfo.setCreateTime(new Date());
                noticeInfo.setStatus(StatusConstant.CUST_NOTICE_STATUS_NO);
                noticeInfo.setCreateBy(user.getUserId().toString());
                noticeInfo.setNoticeEmpNo(user.getUserId().toString());
                noticeInfo.setNoticeTime(DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, DateUtils.getDate() + " " + time + ":00"));
                noticeInfo.setNoticeContent("零星跟进");
                insertCustNoticeInfo(noticeInfo);
                nCount++;
            }
        }
        logger.info("定时任务初始化零星跟进定时通知消息结束，需通知用户数量{}, 初始化消息数量{}", uCount, nCount);
    }
    // 消息推送
    @Override
    public void pushCustNotice() {
        try {
            // 查询所有需要推送的消息-即过了提醒时间且未推送的
            CustNoticeInfo custNoticeInfo = new CustNoticeInfo();
            custNoticeInfo.setStatus("0");
            List<CustNoticeInfo> noticeList = custNoticeInfoMapper.findAllNoticeNeedPush(custNoticeInfo);
            if (CollectionUtils.isNotEmpty(noticeList)) {
                int successCount = 0;
                logger.info("定时推送备忘提醒开始，本次推送数量：" + noticeList.size());
                String tenantId = DynamicDataSourceContextHolder.getDataSourceKey();
                for (CustNoticeInfo noticeInfo : noticeList) {
                    try {
                        //发送消息给前端
                        if(webSocket.onSendByUserId(JSONObject.from(noticeInfo).toString(),tenantId+"_!_"+noticeInfo.getNoticeEmpNo())){
                            noticeInfo.setStatus(StatusConstant.CUST_NOTICE_STATUS_YES);
                            updateCustNoticeInfo(noticeInfo);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.error("pushCustNotice消息推送"+noticeInfo.getId(),e);
                    }
                }
                logger.info("定时推送备忘提醒结束，推送成功数量：" + successCount);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("pushCustNotice消息推送",e);
        }

    }
}
